package com.landun.market.web.controller;

import com.landun.market.exception.AuthenticationException;
import com.landun.market.pojo.domain.AccessToken;
import com.landun.market.pojo.enums.ResponseCode;
import com.landun.market.pojo.enums.UserType;
import com.landun.market.util.HostUtils;
import com.landun.market.web.domain.ApiOut;
import com.landun.market.web.domain.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import java.util.Optional;

/**
 * @author jiang.chuan
 * @date 2018-05-12
 */
@Slf4j
@RestController
@RequestMapping("/oauth2")
public class SecurityController extends AbstractController {
    /**
     * 获取授权令牌
     * http://domain:port/oauth2/token?username=:name&password=:pwd&grantType=password
     *
     * @param loginUser 登录信息
     * @return 授权验证码
     */
    @PostMapping(path = "/token", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiOut<AccessToken> getToken(@RequestBody LoginUser loginUser) {
        // 检查参数
        if (StringUtils.isAnyBlank(loginUser.getUsername(), loginUser.getPassword())) {
            throw new AuthenticationException(ResponseCode.PARAMETER_REQUIRED, "用户名或密码");
        }

        // 登陆类型，默认PC端
        UserType type = Optional.ofNullable(loginUser.getUserType()).orElse(UserType.PLATFORM);

        // 提取真实密码
        String base64Password = new String(Base64.getDecoder().decode(loginUser.getPassword()));
        String password = StringUtils.replaceOnce(base64Password, loginUser.getUsername() + ":", "");

        return new ApiOut.Builder<AccessToken>()
                .data(securityService.login(type, loginUser.getUsername(), password, HostUtils.getRequestIp(httpRequest)))
                .build();
    }

    /**
     * 退出系统
     *
     * @param token 授权令牌
     */
    @RequestMapping(path = "/logout", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiOut<Boolean> logout(@RequestHeader("token") String token) {
        securityService.logout(token, HostUtils.getRequestIp(httpRequest));
        return new ApiOut.Builder<Boolean>().code(ResponseCode.SUCCESS).data(true).build();
    }

    /**
     * 验证授权令牌是否有效
     *
     * @param token 授权令牌
     */
    @RequestMapping(path = "/authenticated", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ApiOut<Boolean> isAuthenticated(@RequestHeader("token") String token) {
        return new ApiOut.Builder<Boolean>()
                .code(ResponseCode.SUCCESS)
                .data(securityService.isAuthenticated(token, HostUtils.getRequestIp(httpRequest)))
                .build();
    }
}
